<?php

namespace app\models;

use yii;
use yii\db\ActiveRecord;
use yii\filters\RateLimitInterface;
use yii\web\IdentityInterface;

class AdminUser extends ActiveRecord implements IdentityInterface //, RateLimitInterface
{
    public $id;
    public $username;
    public $password;
    public $auth_key;
    public $accesstoken;
    public $email;

    const STATUS_ACTIVE=0;

    public static function tableName()
    {
        return '{{%admin_user}}';
    }

    /**
    * 生成 accesstoken
    */
    public function generateApiToken()
    {
        $this->accesstoken = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
    * 校验accesstoken是否有效
    */
    public static function apiTokenIsValid($token)
    {
        if (empty($token)) {
            return false;
        }
        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.apiTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {   
        $user = static::find()->where(['id'=>$id,'status'=>self::STATUS_ACTIVE])->asArray()->one();

        return $user?new static($user):null;
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByaccesstoken($token, $type = null)
    {

        if(!static::apiTokenIsValid($token)) {

            throw new \yii\web\UnauthorizedHttpException("accesstoken 已过期",401);
        }

        $user = static::find()->where(['accesstoken'=>$token,'status'=>self::STATUS_ACTIVE])->asArray()->one();

        return $user?new static($user):null;
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        $user = static::find()->where(['username'=>$username,'status'=>self::STATUS_ACTIVE])->asArray()->one();

        return $user?new static($user):null;
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->auth_key === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return  Yii::$app->getSecurity()->validatePassword($password, $this->password); 
    }
}
